﻿#include "libutils.h"

int uniform_integer(int start, int end)
{
	int base = rand();
	if (base == RAND_MAX)
		return uniform_integer(start, end);
	int range = end - start;
	int remainder = RAND_MAX % range;
	int bucket = RAND_MAX / range;
	if (base < RAND_MAX - remainder)
		return start + base / bucket;
	else
		return uniform_integer(start, end);
}

int get_random(void)
{
	return uniform_integer(0, 100);
}

int get_cs(void *buf, int len)
{
	unsigned char *p = (unsigned char*)buf;
	int cs = 0;
	
	for(int i = 0; i < len; ++i) {
		cs += p[i];
	}

	cs &= 0xFF;	
	return cs;
}

/* bin to 8421BCD */
int bin2bcd(int bin)
{
	return (bin%10) + (bin/10)*16;
}

/* 8421BCD to bin*/
int bcd2bin(int bcd)
{
	return (bcd>>4)*10 + (bcd & 0xf);
}

void mem_dump(void *buf, int len)
{
	int i = 0;

	for(i = 0; i < len; ++i) {
		printf("%02X ", *((unsigned char*)buf +i));
	}
	printf("\n");
}

time_t unix_time(unsigned char *ptime)
{
	struct tm tm1;
	tm1.tm_sec = (int)ptime[0];
	tm1.tm_min = (int)ptime[1];
	tm1.tm_hour = (int)ptime[2];
	tm1.tm_mday = (int)ptime[3];
	tm1.tm_mon = (int)ptime[4] - 1;
	tm1.tm_year = (int)ptime[5] + 100;

#if 0
	printf("%02X %02X %02X %02X %02X %02X\n",
		tm1.tm_year, tm1.tm_mon, tm1.tm_mday,
		tm1.tm_hour, tm1.tm_min, tm1.tm_sec);
#endif

	return mktime(&tm1);
}

__u8 ch2hex(__u8 c)
{
	__u8 v = 0;

	if (c >= '0' && c <= '9') 
		v = c -'0';

	if (c >= 'a' && c <= 'f')
		v = c -'a' + 10;

	if (c >= 'A' && c <= 'F')
		v = c -'A' + 10;
	return v;
}

int str2hex(__u8 *asc, __u8* hex, int len)
{
	unsigned char uc;
	int n;

	if (len % 2){
		return 1;
	}
	
	for (n = 0;n < len / 2; n++) {
		uc = ch2hex(asc[n * 2]);
		uc <<= 4;
		uc += ch2hex(asc[n * 2 + 1]);
		hex[n] = uc;
	}
	return 0;
}
